package com.albaba.designpattern.interpreter.text_002;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Description: 表达式解释器类
 * @Author zx
 * @Date 2025/2/28 14:57
 * @Version 1.0
 */
public class ExpressionInterpreter {

    // Deque双向队列，可以从队列两端增加或删除元素
    private Deque<Expression> numbers = new LinkedList<Expression>();

    public long interpret(String expression) {
        String[] elements = expression.split(" ");

        int length = elements.length;

        for (int i = 0; i < (length + 1) / 2; i++) {
            // 向集合的尾部添加元素
            numbers.addFirst(new NumExpression(elements[i]));
        }

        for (int i = (length + 1) / 2; i < length; i++) {
            String operator = elements[i];
            // 符号必须是 + - * /，否则抛出异常
            boolean isValid = "+".equals(operator) ||
                    "-".equals(operator) ||
                    "*".equals(operator) ||
                    "/".equals(operator);

            if (!isValid) {
                throw new RuntimeException("表达式错误");
            }

            // 获取集合中的数字，移除集合中的第一个元素，并且返回被移除的值
            Expression number1 = numbers.pollFirst();
            Expression number2 = numbers.pollFirst();

            Expression result = null;

            if ("+".equals(operator)) {
                result = new PluExpression(number1, number2);
            } else if ("-".equals(operator)) {
                result = new SubExpression(number1, number2);
            } else if ("*".equals(operator)) {
                result = new MulExpression(number1, number2);
            } else if ("/".equals(operator)) {
                result = new DivExpression(number1, number2);
            }

            long num = result.interpret();
            numbers.addLast(new NumExpression(num));

        }

        if (numbers.size() != 1) {
            throw new RuntimeException("表达式错误");
        }
        return numbers.pop().interpret();
    }

}
